"""
管理后台 - 新闻管理接口
"""
from typing import Optional
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.ext.asyncio import AsyncSession

from app.dependencies import get_db, get_current_user
from app.schemas.common import ResponseModel, PaginatedResponse
from app.schemas.content import NewsCreate, NewsUpdate, NewsResponse
from app.crud.base import CRUDBase
from app.models.content import News


router = APIRouter()
crud_news = CRUDBase[News, NewsCreate, NewsUpdate](News)


@router.get("", response_model=ResponseModel)
async def get_news_list(
    page: int = Query(1, ge=1),
    page_size: int = Query(10, ge=1, le=100),
    category_id: Optional[int] = Query(None),
    status: Optional[int] = Query(None),
    db: AsyncSession = Depends(get_db),
    current_user = Depends(get_current_user)
):
    """
    获取新闻列表
    """
    filters = {}
    if category_id is not None:
        filters["category_id"] = category_id
    if status is not None:
        filters["status"] = status
    
    skip = (page - 1) * page_size
    news_list = await crud_news.get_multi(db, skip=skip, limit=page_size, filters=filters)
    total = await crud_news.get_count(db, filters=filters)
    
    return ResponseModel(
        data=PaginatedResponse(
            total=total,
            page=page,
            page_size=page_size,
            items=[NewsResponse.model_validate(n) for n in news_list]
        )
    )


@router.get("/{news_id}", response_model=ResponseModel)
async def get_news(
    news_id: int,
    db: AsyncSession = Depends(get_db),
    current_user = Depends(get_current_user)
):
    """
    获取新闻详情
    """
    news = await crud_news.get_by_id(db, id=news_id)
    if not news:
        raise HTTPException(status_code=404, detail="新闻不存在")
    
    return ResponseModel(data=NewsResponse.model_validate(news))


@router.post("", response_model=ResponseModel)
async def create_news(
    news_in: NewsCreate,
    db: AsyncSession = Depends(get_db),
    current_user = Depends(get_current_user)
):
    """
    创建新闻
    """
    news = await crud_news.create(db, obj_in=news_in)
    return ResponseModel(
        code=201,
        message="创建成功",
        data=NewsResponse.model_validate(news)
    )


@router.put("/{news_id}", response_model=ResponseModel)
async def update_news(
    news_id: int,
    news_in: NewsUpdate,
    db: AsyncSession = Depends(get_db),
    current_user = Depends(get_current_user)
):
    """
    更新新闻
    """
    news = await crud_news.get_by_id(db, id=news_id)
    if not news:
        raise HTTPException(status_code=404, detail="新闻不存在")
    
    news = await crud_news.update(db, db_obj=news, obj_in=news_in)
    return ResponseModel(
        message="更新成功",
        data=NewsResponse.model_validate(news)
    )


@router.delete("/{news_id}", response_model=ResponseModel)
async def delete_news(
    news_id: int,
    db: AsyncSession = Depends(get_db),
    current_user = Depends(get_current_user)
):
    """
    删除新闻
    """
    success = await crud_news.delete(db, id=news_id)
    if not success:
        raise HTTPException(status_code=404, detail="新闻不存在")
    
    return ResponseModel(message="删除成功")

